package org.robot.scm.platform.monitor;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.robot.scm.platform.AbstractMonitor;
import org.robot.scm.pojos.BaseNotify;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.pojos.platform.FinNewsBaseNotify;
import org.robot.scm.retry.SimpleRetryable;
import org.robot.scm.utils.RequestHelper;

/**
 * 每日财经新闻
 */
@Slf4j
public class FinNewNoticeMonitor extends AbstractMonitor {

    @Override
    public PlatformEnum getPlatform() {
        return PlatformEnum.FINNEWS;
    }

    @SneakyThrows
    @Override
    public BaseNotify doMonitor(BaseConfig config) {
        return new SimpleRetryable(3, 3000).retry(() -> this.read(config), Objects::nonNull);
    }

    public BaseNotify read(BaseConfig config) {
        String result = RequestHelper.get(config.getCurrentPlatform().getNoticeSrc());
        JSONArray array = JSON.parseObject(result).getJSONObject("result").getJSONArray("newslist");
        StringBuilder builder = new StringBuilder();
        String dateTitle = "";
        for (int i = 0; i < array.size(); i++) {
            JSONObject news = (JSONObject) array.get(i);
            String title = news.getString("title");
            if (title.contains("全球市场") && (title.contains("早报") || title.contains("晚报"))) {
                dateTitle = title;
                continue;
            }
            builder.append("▲ ").append(title).append("\n");
        }
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return FinNewsBaseNotify.builder()
                .message(dateTitle + "\n" + (builder.toString().trim()))
                .createDay(date)
                .build();
    }
}
